<template>
  <div class="dish-container">
    <header>
      <el-form :inline="true" class="search-form">
        <el-form-item>
          <el-select v-model="searchRestaurantId">
            <el-option :label="item.name" :value="item.id" v-for="item in restaurants" :key="item.id"/>
          </el-select>
          <el-button style="margin-left: 10px" type="primary" @click="searchCategories"
                     :disabled="searchRestaurantId===''">查询
          </el-button>
        </el-form-item>
      </el-form>
    </header>
    <main>
      <div class="dish-left">
        <el-table :data="categories" style="width: 100%" highlight-current-row
                  @current-change="handleTableCurrentChange">
          <el-table-column prop="name" label="餐厅类别"/>
        </el-table>
        <el-pagination
            style="margin-top: 10px"
            small
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            layout="prev, pager, next"
            :total="total"
            class="mt-4"
        />
      </div>
      <div class="dish-right">
        <div class="title">
          <span>当前餐厅类别：{{ searchCategoryName }}</span>
          <el-button type="primary" @click="addDish" :disabled="searchCategoryId===''">新增</el-button>
        </div>
        <el-table :data="dishList" style="width: 100%">
          <el-table-column prop="id" label="ID" sortable></el-table-column>
          <el-table-column prop="name" label="名称" sortable></el-table-column>
          <el-table-column prop="image" label="图片">
            <template #default="{row}">
              <img :src="row.image" style="width:100px;height:100px;object-fit: cover;border-radius: 12px">
            </template>
          </el-table-column>
          <el-table-column prop="price" label="价格" sortable></el-table-column>
          <el-table-column prop="stock" label="库存" sortable></el-table-column>
          <el-table-column prop="soldOut" label="是否售罄" sortable>
            <template #default="{row}">
              <el-tag :type="row.soldOut ? 'danger' : 'success'">{{ row.soldOut ? '售罄' : '有货' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="150">
            <template #default="{row}">
              <el-button size="small" type="primary" @click="editDish(row)">编辑</el-button>
              <el-button size="small" type="danger" @click="deleteDish(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </main>
    <el-dialog :title="isEdit?'编辑菜品内容':'新增菜品内容'" v-model="dialogVisible">
      <el-form :model="currentDish" :rules="rules" ref="dishForm" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="currentDish.name"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="currentDish.description" textrea/>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="currentDish.price" :step="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="是否售罄">
          <el-switch v-model="currentDish.soldOut"></el-switch>
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="currentDish.stock" :step="1"></el-input-number>
        </el-form-item>
        <el-form-item label="图片">
          <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="http://127.0.0.1:8080/api/upload/image"
              :headers="{Authorization:getToken}"
              :on-success="handleUploadSuccess"
              list-type="picture"
              :before-upload="beforeUpload"
          >
            <el-button type="primary">点击上传图片</el-button>
            <template #tip>
              <div class="el-upload__tip">
                jpg/png files with a size less than 20MB
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveDish">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {computed, reactive, toRefs} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {getCategoryByRestaurantId} from "@/api/category";
import {getRestaurantList} from "@/api/restaurant";
import {
  createDish,
  deleteDishById,
  getDishByCategoryId,
  getDishById,
  getDishByRestaurantId,
  updateDish
} from "@/api/dish";
import {getUserToken} from "@/utils/userIsLogin";

export default {
  setup() {
    const state = reactive({
      dishList: [],
      categories: [], // 分类数据
      total: 10, // 数据总数
      currentPage: 1, // 当前页码
      pageSize: 20, // 每页显示数量
      currentDish: null, // 当前编辑的分类对象
      dialogVisible: false, // 编辑对话框是否可见
      rules: {
        name: [{required: true, message: '请输入名称', trigger: 'blur'}],
        price: [{required: true, message: '请输入价格', trigger: 'blur'}],
        stock: [{required: true, message: '请输入库存', trigger: 'blur'}],
      },
      searchRestaurantId: '', // 查询指定餐厅下的菜品类别的餐厅ID
      searchCategoryId: '', // 查询指定餐厅下的菜品类别的分类ID
      searchCategoryName: '',// 查询指定餐厅下的菜品类别的分类名称
      restaurants: [],
      isEdit: false, // 是否是编辑
      fileList: [], // 上传的图片列表
    })
    // 通过指定的菜品类型id获取菜品数据
    const getDishesByCategoryId = async () => {
      if (state.searchCategoryId === '') {
        ElMessage.error('请选择分类')
        return
      }
      try {
        const response = await getDishByCategoryId(state.searchCategoryId)
        if (response.msg === '请求成功') {
          state.dishList = response.data
          state.fileList = []
          state.currentDish = {}
        } else {
          ElMessage.error('获取菜品数据失败')
        }
      } catch (e) {
        ElMessage.error('获取菜品数据失败');
        console.log(e)
      }
    }
    // 获取当前餐厅下的菜品内容列表
    const getDishList = async () => {
      const restaurantId = state.searchRestaurantId
      if (!restaurantId) {
        ElMessage.error('请选择餐厅')
        return
      }
      try {
        const response = await getDishByRestaurantId(restaurantId)
        if (response.msg === '请求成功') {
          state.dishList = response.data
        } else {
          ElMessage.error('获取菜品数据失败')
        }
      } catch (e) {
        ElMessage.error('获取菜品数据失败')
        console.log(e)
      }
    }
    // 获取餐厅数据
    const getRestaurants = async () => {
      try {
        const response = await getRestaurantList()
        if (response.msg === '请求成功') {
          state.restaurants = response.data
        } else {
          ElMessage.error('获取餐厅数据失败')
        }
      } catch (e) {
        ElMessage.error('获取餐厅数据失败')
        console.log(e)
      }
    }
    // 查询指定餐厅下的菜品类别
    const searchCategories = async () => {
      const restaurantId = state.searchRestaurantId
      if (!restaurantId) {
        ElMessage.error('请选择餐厅')
        return
      }
      try {
        const response = await getCategoryByRestaurantId({
          id: restaurantId,
          page: state.currentPage,
          limit: state.pageSize
        })
        if (response.msg === '请求成功') {
          state.categories = response.data.list
          state.total = response.data.total
          getDishList()// 获取当前餐厅下的菜品内容列表并进行展示
        } else {
          ElMessage.error('获取分类数据失败')
        }
      } catch (e) {
        console.log(e)
      }
    }
    // 分页器页码大小变化回调
    const handleSizeChange = (pageSize) => {
      state.pageSize = pageSize
      if (state.searchRestaurantId) {
        searchCategories()
      } else {
        return;
      }
    }
    // 分页器当前页码变化回调
    const handleCurrentChange = (currentPage) => {
      state.currentPage = currentPage
      if (state.searchRestaurantId) {
        searchCategories()
      } else {
        return
      }
    }
    // 切换菜品类别
    const handleTableCurrentChange = (val) => {
      state.searchCategoryId = val.id;
      state.searchCategoryName = val.name
      getDishesByCategoryId()
    };

    // 编辑菜品
    const editDish = async (row) => {
      const res = await getDishById(row.id)
      state.currentDish = res.data
      state.fileList = [{
        name: 'food.jpg',
        url: state.currentDish.image
      }]
      state.dialogVisible = true
      state.isEdit = true
    }

    // 删除菜品
    const deleteDish = (row) => {
      ElMessageBox.confirm('确定删除该菜品吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(async() => {
        // 模拟删除菜品
        await deleteDishById(row.id)
        ElMessage.success('删除成功')
        if(state.searchCategoryId===''){
          getDishList()
        }else{
          getDishesByCategoryId()
        }
      }).catch(() => {
      })
    }
    // 保存菜品
    const saveDish = async () => {
      if (state.isEdit) {
        const id = state.currentDish.id
        const saveObj = {
          name: state.currentDish.name,
          description: state.currentDish.description,
          price: state.currentDish.price,
          image: state.currentDish.image,
          stock: state.currentDish.stock,
          restaurantId: state.searchRestaurantId,
        }
        await updateDish(id, saveObj)
        state.dialogVisible = false
        ElMessage.success('修改菜品成功')
      } else {
        const saveObj = {
          name: state.currentDish.name,
          description: state.currentDish.description,
          price: state.currentDish.price,
          image: state.currentDish.image,
          categoryId: state.searchCategoryId,
          stock: state.currentDish.stock,
          restaurantId: state.searchRestaurantId,
        }
        await createDish(saveObj)
        state.dialogVisible = false
        ElMessage.success('新增菜品成功')
      }
      if (state.searchCategoryId === '') {
        getDishList()
      } else {
        getDishesByCategoryId()
      }
      state.isEdit = false
      state.currentDish = {}
    }

    // 添加菜品
    const addDish = () => {
      state.currentDish = {
        name: '',
        price: 0,
        categoryId: null,
        stock: 0,
      }
      state.dialogVisible = true
    }

    // 处理上传成功地回调
    const handleUploadSuccess = (response) => {
      // 如果上传成功，将文件路径保存到 currentIte。image
      if (response.msg === '请求成功') {
        state.currentDish.image = response.data.uploadUrl
        console.log('上传成功！文件路径为：', response.data.uploadUrl);
      } else {
        // 上传失败，弹出提示
        ElMessage.error('上传失败，请重试！');
      }
    }

    // 在上传之前的操作
    const beforeUpload = (file) => {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
      if (!isJpgOrPng) {
        ElMessage.error('上传文件只能是 JPG 或 PNG 格式！');
        return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 20;
      if (!isLt2M) {
        ElMessage.error('上传文件大小不能超过 20MB！');
        return false;
      }
      return true;
    }
    // 获取token
    const getToken = computed(() => {
      return `Bearer ${getUserToken()}`
    })

    const dishInit = () => {
      getRestaurants()
      state.isEdit = false
    }
    dishInit()
    return {
      ...toRefs(state),
      searchCategories,
      handleSizeChange,
      handleCurrentChange,
      handleTableCurrentChange,
      saveDish,
      addDish,
      deleteDish,
      editDish,
      handleUploadSuccess,
      beforeUpload,
      getToken
    }
  }
}
</script>

<style scoped lang="scss">
.dish-container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-start;
  flex-direction: column;

  header {
    height: 50px;
    width: 100%;
    display: flex;
  }

  main {
    height: calc(100% - 50px);
    width: 100%;
    display: flex;

    .dish-left {
      width: 20%;
      height: 100%;
      background-color: #fff;
      border-radius: 12px;
      border: 1px solid #ebeef5;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      align-items: center;
    }

    .dish-right {
      width: 80%;
      height: 100%;
      background-color: #fff;

      .title {
        height: 40px;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-left: 10px;
        font-weight: 600;
      }
    }
  }
}
</style>
